﻿using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace DVK.ConstantsGenerator
{
    public static class ListsGenerator
    {
        public const string ElementField = "Field";
        public const string ElementListInstance = "ListInstance";
        public const string AttributeType = "Type";
        public const string AttributeUrl = "Url";
        public const string AttributeName = "Name";
        public const string AttributeID = "Id";
        public const string AttributeList = "List";
        public const string AttributeTitle = "Title";

        public static XElement _siteColumnsXml;
        public static XElement _listsXml;

        public static string AttributeTypeValueChoice = "Choice";

        public static void Generate()
        {
            string path = ConfigurationManager.AppSettings[Constants.ListsConstantsOutput];

            FileStream file = File.Create(path, 1024, FileOptions.WriteThrough);
            StreamWriter writer = new StreamWriter(file);

            writer.WriteLine(GeneratorHelper.GetNamespaceString(Constants.Namespace));
            writer.WriteLine(GeneratorHelper.GetSummary("Generated class: " + GeneratorHelper.ParseName("Lists")));
            writer.WriteLine(
                GeneratorHelper.GetClassString(GeneratorHelper.ParseName("Lists"))
            );

            var query = from list in GetListsXml().Elements(GeneratorHelper.GetName(ElementListInstance))
                        select list;

            foreach (var field in query)
            {
                string id = field.Attribute(AttributeID).Value;
                string url = field.Attribute(AttributeUrl).Value;
                string[] splittedUrl = url.Split('/');
                string listName = splittedUrl[splittedUrl.Length -1];

                writer.WriteLine(
                    GeneratorHelper.GetClassString(GeneratorHelper.ParseName(listName))
                );
                writer.WriteLine(
                            GeneratorHelper.GetConstantFieldString(GeneratorHelper.ParseName(AttributeID), id)
                        );
                writer.WriteLine(
                            GeneratorHelper.GetConstantFieldString(GeneratorHelper.ParseName(AttributeUrl), url)
                        );

                writer.WriteLine(GeneratorHelper.GetEndString());
            }
            writer.WriteLine(GeneratorHelper.GetEndString());
            writer.WriteLine(GeneratorHelper.GetEndString());
            writer.Flush();
            writer.Close();
        }

        public static XElement GetListsXml()
        {
            if (_listsXml != null)
                return _listsXml;

            _listsXml = XElement.Load(
                    GeneratorHelper.GetPathFromAppSettings(Constants.ListsPath)
                );
            return _listsXml;
        }
    }
}
